<template>
  <div class="form-design-preview">
    <draggable
      v-model="formCards"
      item-key="cardCode"
      group="preview"
      animation="200"
      class="card-draggable"
      @start="drag = true"
      @end="drag = false"
      @add="onAddCard"
    >
      <template #item="{ element }">
        <CardContainer
          :mode="mode"
          :curCardCode="curCardCode"
          :card="element"
          :formCards="formCards"
          @click="onCardClick(element)"
        />
      </template>
    </draggable>
    <div v-if="!formCards.length" class="preview-empty">
      <img :src="imgDesigner" />
      <p class="text">拖入或点击添加左侧控件绘制表单</p>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, computed } from 'vue';
import { useStore } from 'vuex';
import { message } from 'ant-design-vue';
import draggable from 'vuedraggable';
import cloneDeep from 'lodash/cloneDeep';
import { FormCard } from '@/model/types/formCard';
import CardContainer from '@/engine/components/CardContainer.vue';
import imgDesigner from '@/assets/imgs/flow/designer.svg';

export default defineComponent({
  name: 'FormDesignPreview',
  components: {
    draggable,
    CardContainer,
  },
  setup() {
    const store = useStore();
    const mode = computed(() => store.state.formDesign.mode);
    const formCards = computed({
      get: () => store.state.formDesign.form.formCards,
      set: (val) => {
        store.commit('formDesign/SetFormCards', val);
      },
    });
    const curCardCode = computed({
      get: () => store.state.formDesign.curCardCode,
      set: (val) => {
        store.commit('formDesign/SetCurCardCode', val);
      },
    });
    const drag = ref(false);
    const onAddCard = (data: any) => {
      const card: FormCard = data.item.__draggable_context.element;
      // 系统卡片不允许重复
      if (card.cardCode.indexOf('_copy') > -1) {
        const filterList = formCards.value.filter(
          (it: any) => it.cardCode !== card.cardCode,
        );
        formCards.value = cloneDeep(filterList);
        message.warning('系统卡片不允许重复');
      } else {
        curCardCode.value = card.cardCode;
        // 防止formCards和拖拽来的对象存在引用关系
        formCards.value = cloneDeep(formCards.value);
      }
    };
    const onCardClick = (card: any) => {
      curCardCode.value = card.cardCode;
    };

    return {
      imgDesigner,
      mode,
      formCards,
      drag,
      curCardCode,
      onAddCard,
      onCardClick,
    };
  },
});
</script>
<style lang="less" scoped>
.form-design-preview {
  position: relative;
  flex: 1;
  height: 100%;
  margin: 0 12px;
  padding: 12px 0;
  background-color: @rb-body-background;
  .card-draggable {
    height: 100%;
    overflow-y: auto;
  }
  .preview-empty {
    position: absolute;
    left: 50%;
    top: 40%;
    transform: translate(-50%, -50%);
    .text {
      margin-top: 8px;
      text-align: center;
      color: @rb-disabled-color;
    }
  }
}
</style>
